﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roslyn.Compilers.CSharp;

namespace WeakEvent
{
    internal class WeakEventClassVisitor : SyntaxVisitor<bool>
    {
        public override bool Visit(SyntaxNode node)
        {
            return base.Visit(node) ? true : node.ChildNodes().Any(n => Visit(n));
        }

        protected override bool VisitBlock(BlockSyntax node)
        {
            BinaryExpressionSyntax assignment; 
            ExpressionStatementSyntax expressionStatementSyntax;
            return IsWeakHandler(node, out assignment, out expressionStatementSyntax);
        }

        public static bool IsWeakHandler(BlockSyntax node, out BinaryExpressionSyntax assignment, out ExpressionStatementSyntax expressionStatementSyntax)
        {
            IdentifierNameSyntax identifierName;
            assignment = default(BinaryExpressionSyntax);
            expressionStatementSyntax = default(ExpressionStatementSyntax);
            return node.Statements.Count == 2 && node.Statements[0].ChildNodes().Count() == 1 && (assignment = node.Statements[0].ChildNodes().First() as BinaryExpressionSyntax) != null && (assignment.Kind == SyntaxKind.AddAssignExpression || assignment.Kind == SyntaxKind.SubtractAssignExpression) && (identifierName = assignment.Right as IdentifierNameSyntax) != null && identifierName.GetText() == "weak" && (expressionStatementSyntax = node.Statements[1] as ExpressionStatementSyntax) != null;
        }
    }
}
